package com.lagou.ioc;

import org.reflections.Reflections;

import java.lang.reflect.Constructor;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @description:
 * @author: 任嘉豪
 * @version: V1.0
 * @date: 20-6-7 下午2:33
 **/
public class ApplicationContext {

    public final static Map<String,BeanWrap> instance = new ConcurrentHashMap<>();

    public static BeanWrap getObjectById(String requestId){
        return instance.get(requestId);
    }

    public static void init(Class<?> cls){
        String basePackage = cls.getPackage().getName();
        init(basePackage);
    }

    public static void init(String basePackage){
        Reflections reflections = new Reflections(basePackage);
        Set<Class<?>> classSet = reflections.getTypesAnnotatedWith(Service.class);

        for (Class<?> cls : classSet) {
            Service annotation = cls.getAnnotation(Service.class);
            String beanId = annotation.value();
            try {
                Constructor<?> constructor = cls.getConstructor();
                Object o = constructor.newInstance();

                BeanWrap beanWrap = new BeanWrap();
                beanWrap.setCls(cls);
                beanWrap.setBeanInstance(o);
                instance.put(beanId, beanWrap);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        System.out.println("---初始化实例完成---");
    }
}
